package com.fenxiangle.yueding.feature.publish.view;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.fenxiangle.yueding.R;
import com.fenxiangle.yueding.common.alipay.PayResult;
import com.fenxiangle.yueding.entity.bo.AliPayBo;
import com.fenxiangle.yueding.entity.bo.MyAccountBo;
import com.fenxiangle.yueding.entity.bo.OrderBo;
import com.fenxiangle.yueding.feature.focus.view.WithdrawDepositActivity;
import com.fenxiangle.yueding.feature.publish.contract.PayContract;
import com.fenxiangle.yueding.feature.publish.dependencies.pay.DaggerPayComponent;
import com.fenxiangle.yueding.feature.publish.dependencies.pay.PayPresenterModule;
import com.fenxiangle.yueding.feature.publish.presenter.PayPresenter;
import com.fenxiangle.yueding.wxapi.WXPayEntryActivity;
import com.suozhang.framework.entity.bo.BaseEntity;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.T;
import com.suozhang.framework.utils.logger.Logger;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

public class PayActivity extends BaseActivity implements PayContract.View {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.wi_right)
    ImageView wiRight;
    @BindView(R.id.bank_name)
    TextView bankName;
    @BindView(R.id.bank_time)
    TextView bankTime;
    @BindView(R.id.wi_money)
    TextView wiMoney;
    @BindView(R.id.wi_balance)
    TextView wiBalance;
    @BindView(R.id.btn_all)
    TextView btnAll;
    @BindView(R.id.btn_deposit)
    TextView btnDeposit;
    @BindView(R.id.check_alibb)
    CheckBox checkAlibb;
    @BindView(R.id.check_weichat)
    CheckBox checkWeichat;
    @BindView(R.id.pay_money_title)
    TextView payMoneyTitle;
    @BindView(R.id.tv_pay_type_title)
    TextView tvPayTypeTitle;
    private int payType;
    private OrderBo mPayMoney;
    private String publishType;
    @Inject
    PayContract.Presenter mPresenter;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_pay;
    }

    @Override
    protected void initInjector() {
        DaggerPayComponent.builder().payPresenterModule(new PayPresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        initToolBar(toolbar, "支付", true, true);
    }

    @Override
    protected void initData() {
        mPayMoney = (OrderBo) this.getIntent().getSerializableExtra("no");
        wiMoney.setText("" + mPayMoney.getTotalPrice());
        publishType = getIntent().getStringExtra("publishType");

        IntentFilter filter = new IntentFilter(WXPayEntryActivity.action);
        registerReceiver(broadcastReceiver, filter);
    }

    @OnClick({R.id.check_alibb, R.id.check_weichat, R.id.btn_deposit, R.id.layout_alibb, R.id.layout_weichat})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.check_alibb:
                checkAlibb.setChecked(true);
                checkWeichat.setChecked(false);
                payType = 0;
                break;
            case R.id.check_weichat:
                checkAlibb.setChecked(false);
                checkWeichat.setChecked(true);
                payType = 1;
                break;
            case R.id.layout_alibb:
                checkAlibb.setChecked(true);
                checkWeichat.setChecked(false);
                payType = 0;
                break;
            case R.id.layout_weichat:
                checkAlibb.setChecked(false);
                checkWeichat.setChecked(true);
                payType = 1;
                break;
            case R.id.btn_deposit:
                if (!TextUtils.isEmpty(publishType)) {//发布需求
                    mPresenter.getPayData("6", payType, mPayMoney.getOrderId(), mPayMoney.getTotalPrice());
                } else {//发布邀约
                    mPresenter.getPayData("5", payType, mPayMoney.getOrderId(), mPayMoney.getTotalPrice());
                }
                break;
        }
    }

    @Override
    public void showAliPayData(String aliPayData) {
        toAlipay(aliPayData);
    }

    @Override
    public void showWxPayData(AliPayBo.WechatBo wechatBo) {
        toWxPay(wechatBo);
    }

    @Override
    public void showError(String error) {

    }

    @Override
    public void showAccountSuccess(MyAccountBo aliPayData) {

    }


    private void toWxPay(AliPayBo.WechatBo wxPayBo) {
        IWXAPI api = WXAPIFactory.createWXAPI(this, wxPayBo.getAppid());
        api.registerApp(wxPayBo.getAppid());
        PayReq req = new PayReq();
        req.appId = wxPayBo.getAppid();
        req.partnerId = wxPayBo.getPartnerid();
        req.prepayId = wxPayBo.getPrepayid();
        req.nonceStr = wxPayBo.getNoncestr();
        req.timeStamp = wxPayBo.getTimestamp();
        req.packageValue = "Sign=WXPay";
        req.sign = wxPayBo.getSign();
        api.sendReq(req);
    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                if (intent.getBooleanExtra("data", false)) {
                    startActivity(new Intent(PayActivity.this, MyPublishActivity.class));
                    finish();
                }
            }
        }

    };

    /**
     * 支付宝支付
     */
    private void toAlipay(String msg) {

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String, String> result = alipay.payV2(msg, true);
                Logger.e("msg-------->", result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {

                        startActivity(new Intent(PayActivity.this, MyPublishActivity.class));
                        finish();

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        T.showShort("支付失败");
                    }
                    break;
                }
                default:
                    break;
            }
        }

    };


}
